﻿#include "sender.h"

struct multicast_sender::multicast_sender_impl {
    boost::asio::io_context& io_context_;
    boost::asio::ip::udp::endpoint endpoint_;
    boost::asio::ip::udp::socket socket_;
    std::string message_;
    multicast_sender_impl(boost::asio::io_context& io_context
        , const boost::asio::ip::address& multicast_address
        , const unsigned short multicast_port
        , const boost::asio::ip::udp::endpoint& bind_endpoint)
        : io_context_(io_context)
        , socket_(io_context, endpoint_.protocol())
        , endpoint_(multicast_address, multicast_port)
    {
        socket_.bind(bind_endpoint);
    }
};

multicast_sender::multicast_sender(boost::asio::io_context& io_context
    , const boost::asio::ip::address& multicast_address
    , const unsigned short multicast_port
    , const boost::asio::ip::udp::endpoint& bind_endpoint) 
{
    impl = new multicast_sender_impl(io_context, multicast_address, multicast_port, bind_endpoint);
}

multicast_sender::~multicast_sender()
{
    delete impl;
}


void multicast_sender::async_send_to(const std::vector<char>& data
    , std::function<void(boost::system::error_code ec, std::size_t)> handler)
{
    impl->socket_.async_send_to(
        boost::asio::buffer(data, data.size()), impl->endpoint_,
        handler);
}

void multicast_sender::async_send_to(const char* data, size_t length
    , std::function<void(boost::system::error_code ec, std::size_t)> handler)
{
    impl->socket_.async_send_to(
        boost::asio::buffer(data, length), impl->endpoint_
        , handler);
}

void multicast_sender::async_send_to(const std::string& data
    , std::function<void(boost::system::error_code ec, std::size_t)> handler)
{
    impl->message_ = data;
    impl->socket_.async_send_to(
        boost::asio::buffer(impl->message_), impl->endpoint_
        , handler);
}